@echo off
setlocal enabledelayedexpansion

chcp 65001 >NUL

echo [%DATE% %TIME%] Jenkins Windows build starting...

rem 计算绝对路径，避免 Jenkins 工作目录差异
set "SCRIPT_DIR=%~dp0"
set "APP_DIR=%SCRIPT_DIR%nestjs-app"
set "DIST_MAIN=%APP_DIR%\dist\main.js"

rem 切到 NestJS 项目目录（绝对路径）
cd /d "%APP_DIR%"

rem 必要环境变量（如需修改请在 Jenkins 中以参数或凭证注入）
set PORT=8206
set DB_HOST=43.143.253.188
set DB_PORT=3306
set DB_USER=nextjs
set DB_PASS=yEAiRE2jcxTyRBy5
set DB_NAME=nextjs

echo [%DATE% %TIME%] Installing dependencies...
call npm ci >NUL 2>&1
if errorlevel 1 (
  echo npm ci failed, fallback to npm install
  call npm install --no-fund --no-audit
  if errorlevel 1 (
    echo npm install failed
    exit /b 1
  )
)

echo [%DATE% %TIME%] Building project...
call npm run build
if errorlevel 1 (
  echo Build failed
  exit /b 1
)

rem 校验构建产物（绝对路径）
if not exist "%DIST_MAIN%" (
  echo %DIST_MAIN% not found. Build may have failed or output path changed.
  exit /b 1
)

rem 校验 PM2 配置文件（ecosystem）
set "ECOSYSTEM_FILE=%APP_DIR%\ecosystem.config.cjs"
if not exist "%ECOSYSTEM_FILE%" (
  echo %ECOSYSTEM_FILE% not found. PM2 ecosystem file is required.
  exit /b 1
)

rem 确保日志目录存在（ecosystem 中使用 logs/）
if not exist "%APP_DIR%\logs" (
  mkdir "%APP_DIR%\logs"
)

echo [%DATE% %TIME%] Deploying with PM2...

rem 设置生产环境变量及 PM2 运行目录（Jenkins 服务账号通常无用户目录权限）
set NODE_ENV=production
set PM2_HOME=%APP_DIR%\.pm2
set NO_UPDATE_NOTIFIER=1

rem 使用 npx 运行 PM2，避免全局安装与 PATH 问题
call npx --yes pm2 -v >NUL 2>&1

rem 通过 ecosystem 进行启动或重载
rem 选择 PM2 可执行（优先使用全局 pm2，否则回退 npx pm2）
where pm2 >NUL 2>&1
if errorlevel 1 (
  set "PM2_CMD=npx --yes pm2"
) else (
  set "PM2_CMD=pm2"
)

echo Starting PM2 via ecosystem ...
call %PM2_CMD% start "%ECOSYSTEM_FILE%" --env production --update-env
if errorlevel 1 (
  echo PM2 start/reload failed
  exit /b 1
)

rem 保存当前 PM2 进程列表，便于开机自启（若已配置 pm2 startup）
call %PM2_CMD% save

echo [%DATE% %TIME%] Build succeeded.
exit /b 0

